/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import com.google.common.io.Files;
import com.mcgrobot.domain.FileInfo;
import com.mcgrobot.service.FsService;

@Service
public class FsServiceImpl implements FsService {

	@Override
	public List<FileInfo> getCurDirDetails(String path) {
		List<FileInfo> fileInfoList = new ArrayList<>();
        File file = new File(path);
        int num = 0;
        Iterable<File> childrens = Files.fileTreeTraverser().children(file);
        for (File children : childrens) {
        	String fullPath = children.getAbsolutePath();
        	int pos = fullPath.lastIndexOf(File.separator);
        	FileInfo fileInfo = new FileInfo();
        	fileInfo.setId(num++);
        	fileInfo.setFileType(children.isDirectory() ? "dir":"file");
        	fileInfo.setFilePath(fullPath.substring(0, (pos + 1)).replaceAll("\\\\", "/"));
        	fileInfo.setFileName(fullPath.substring(pos + 1));
        	fileInfo.setModifyDate(new Date(children.lastModified()));
        	if(children.isDirectory()) {
        		fileInfo.setFileSize(FileUtils.sizeOfDirectory(children));
        	} else {
        		fileInfo.setFileSize(children.length());
        	}
        	fileInfoList.add(fileInfo);
        }
        
        return fileInfoList;
	}

}
